import React, { useEffect, useState } from "react";
import CommandAPI from "../../api/commandApi";
import { Command, CommandCreate } from "../../types/Command";

const CommandPage = () => {
    const [commands, setCommands] = useState<Command[]>([]);
    const [showModal, setShowModal] = useState(false);
    const [currentCommand, setCurrentCommand] = useState<CommandCreate & Partial<{ id: number }> | null>(null);
    const [activeTab, setActiveTab] = useState('list');

    
const tabs = [
    { key: 'list', label: '命令列表' },
    { key: 'create', label: '新建命令' },
    { key: 'history', label: '执行历史' },
  ];

    const fetchCommands = async () => {
        const res = await CommandAPI.getAll();
        setCommands(res.data);
    };

    useEffect(() => {
        fetchCommands();
    }, []);

    const handleDeploy = async (id: number) => {
        if (!window.confirm("确定要部署该命令吗？")) return;
        try {
            const res = await CommandAPI.deploy(id);
            alert(res.data.message);
            fetchCommands();
        } catch (error: any) {
            alert(error?.response?.data?.detail || "部署失败");
        }
    };

    const handleOffline = async (id: number) => {
        if (!window.confirm("确定要下线该命令吗？")) return;
        try {
            const res = await CommandAPI.offline(id);
            alert(res.data.message);
            fetchCommands();
        } catch (error: any) {
            alert(error?.response?.data?.detail || "操作失败");
        }
    };

    const handleDelete = async (id: number) => {
        if (!window.confirm("确定要删除该命令吗？")) return;
        await CommandAPI.delete(id);
        fetchCommands();
    };

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        if (!currentCommand?.command) {
            alert("请填写命令内容");
            return;
        }

        try {
            if (currentCommand.id) {
                await CommandAPI.update(currentCommand.id, currentCommand);
            } else {
                await CommandAPI.create(currentCommand);
            }

            setShowModal(false);
            setCurrentCommand(null);
            fetchCommands();
        } catch (error: any) {
            alert(error?.response?.data?.detail || "操作失败");
        }
    };

    const handleEdit = (cmd: Command) => {
        setCurrentCommand({ ...cmd });
        setShowModal(true);
    };

    return (
<div className="p-4">
      {/* Tab 导航 */}
      <div className="flex border-b border-gray-300 mb-4">
        {tabs.map((tab) => (
          <button
            key={tab.key}
            onClick={() => setActiveTab(tab.key)}
            className={`px-4 py-2 -mb-px border-b-2 font-medium ${
              activeTab === tab.key
                ? 'border-blue-500 text-blue-500'
                : 'border-transparent text-gray-500 hover:text-gray-700'
            }`}
          >
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab 内容 */}
      <div>
        {activeTab === 'list' &&    <div className="p-6 bg-gray-50 dark:bg-gray-900 min-h-screen">
            <div className="flex justify-between items-center mb-6">
                <h1 className="text-3xl font-bold text-gray-900 dark:text-white">命令管理</h1>
                <button
                    className="bg-blue-600 text-white py-2 px-5 rounded-lg hover:bg-blue-700 shadow"
                    onClick={() => {
                        setCurrentCommand({ command: "", description: "", status: false });
                        setShowModal(true);
                    }}
                >
                    + 新增命令
                </button>
            </div>

            <div className="overflow-x-auto rounded-lg shadow">
                <table className="w-full text-sm text-left text-gray-600 dark:text-gray-300">
                    <thead className="text-xs uppercase bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300">
                        <tr>
                            <th className="px-6 py-3">ID</th>
                            <th className="px-6 py-3">命令</th>
                            <th className="px-6 py-3">描述</th>
                            <th className="px-6 py-3">状态</th>
                            <th className="px-6 py-3 text-right">操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {commands.map(cmd => (
                            <tr key={cmd.id} className="bg-white border-b dark:bg-gray-800 dark:border-gray-700 hover:bg-gray-50 dark:hover:bg-gray-600">
                                <td className="px-6 py-4">{cmd.id}</td>
                                <td className="px-6 py-4">{cmd.command}</td>
                                <td className="px-6 py-4">{cmd.description || "-"}</td>
                                <td className="px-6 py-4">{cmd.status ? "已部署" : "未部署"}</td>
                                <td className="px-6 py-4 flex justify-end space-x-2">
                                    <button
                                        className="bg-blue-500 text-white py-1.5 px-3 rounded hover:bg-blue-600"
                                        onClick={() => handleEdit(cmd)}
                                    >
                                        编辑
                                    </button>
                                    {cmd.status ? (
                                        <button
                                            className="bg-green-500 text-white py-1.5 px-3 rounded hover:bg-green-600"
                                            onClick={() => handleOffline(cmd.id)}
                                        >
                                            下线
                                        </button>
                                    ) : (
                                        <button
                                            className="bg-green-500 text-white py-1.5 px-3 rounded hover:bg-green-600"
                                            onClick={() => handleDeploy(cmd.id)}
                                        >
                                            部署
                                        </button>
                                    )}
                                    <button
                                        className="bg-red-500 text-white py-1.5 px-3 rounded hover:bg-red-600"
                                        onClick={() => handleDelete(cmd.id)}
                                    >
                                        删除
                                    </button>
                                </td>
                            </tr>
                        ))}
                        {commands.length === 0 && (
                            <tr>
                                <td colSpan={5} className="px-6 py-4 text-center text-gray-500">暂无数据</td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>

            {/* 弹窗 */}
            {showModal && (
                <div className="fixed inset-0 flex items-center justify-center z-50">
                    <div className="absolute inset-0 bg-black bg-opacity-40" onClick={() => setShowModal(false)}></div>
                    <div className="bg-white dark:bg-gray-800 p-6 rounded-xl shadow-lg z-10 w-full max-w-md">
                        <h2 className="text-2xl font-semibold mb-4 text-gray-900 dark:text-white">
                            {currentCommand?.id ? "编辑命令" : "新增命令"}
                        </h2>
                        <form onSubmit={handleSubmit} className="space-y-4">
                            <div>
                                <label className="block text-gray-700 dark:text-gray-300 mb-1">命令</label>
                                <input
                                    type="text"
                                    value={currentCommand?.command || ""}
                                    onChange={e => setCurrentCommand({ ...currentCommand, command: e.target.value })}
                                    required
                                    className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                                />
                            </div>
                            <div>
                                <label className="block text-gray-700 dark:text-gray-300 mb-1">描述</label>
                                <input
                                    type="text"
                                    value={currentCommand?.description || ""}
                                    onChange={e => setCurrentCommand({ ...currentCommand, description: e.target.value })}
                                    className="w-full px-3 py-2 border rounded-lg border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-gray-900 dark:text-white"
                                />
                            </div>
                            <div className="flex items-center space-x-2">
                                <input
                                    type="checkbox"
                                    checked={currentCommand?.status ?? false}
                                    onChange={e => setCurrentCommand({ ...currentCommand, status: e.target.checked })}
                                    className="w-4 h-4"
                                />
                                <span className="text-gray-700 dark:text-gray-300">启用命令</span>
                            </div>

                            <div className="flex justify-end space-x-3 pt-2">
                                <button
                                    type="button"
                                    className="bg-gray-400 text-white py-2 px-4 rounded hover:bg-gray-500"
                                    onClick={() => setShowModal(false)}
                                >
                                    取消
                                </button>
                                <button
                                    type="submit"
                                    className="bg-blue-600 text-white py-2 px-4 rounded hover:bg-blue-700"
                                >
                                    保存
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            )}
        </div>}
        {activeTab === 'create' && <div>这是新建命令内容</div>}
        {activeTab === 'history' && <div>这是执行历史内容</div>}
      </div>
    </div>


     
    );
};

export default CommandPage;
